// Fill out your copyright notice in the Description page of Project Settings.

#include "RPG.h"
#include "PickupActor.h"
#include "RPGCharacter.h"
#include "InventoryItemStruct.h"
#include "DataTableFunctions.h"
#include "RPGWorldSettings.h"
#include "Engine.h"
#include "UnrealNetwork.h"


APickupActor::APickupActor(const FObjectInitializer& ObjectInitializer)
	: Super(ObjectInitializer)
{
	ItemID = 0;

	TextRender = ObjectInitializer.CreateDefaultSubobject<UTextRenderComponent>(this, TEXT("TextRender"));
	TextRender->AttachTo(RootComponent);
}

void APickupActor::GetLifetimeReplicatedProps(TArray<FLifetimeProperty>& OutLifetimeProps) const
{
	Super::GetLifetimeReplicatedProps(OutLifetimeProps);

	DOREPLIFETIME(APickupActor, ItemID);
}



bool APickupActor::OnUsed_Implementation(ACharacter* Character)
{
	ARPGCharacter* myChar = Cast<ARPGCharacter>(Character);

	if (myChar)
	{
		myChar->ServerPegarItem(ItemID);

		Destroy();

		return true;
	}

	return false;
}

void APickupActor::OnConstruction(const FTransform& Transform)
{
	ARPGWorldSettings* ws = Cast<ARPGWorldSettings>(GetWorld()->GetWorldSettings());

	if (ws && ItemID > 0)
	{
		UDataTable* table = ws->ItemDataTable;
		if (table)
		{
			FInventoryItemStruct* row = UDataTableFunctions::GetItemDataPtr(ItemID);

			if (row)
			{
				UStaticMesh* mesh = UDataTableFunctions::GetAssetPtr<UStaticMesh>(row->Modelo);

				Mesh->SetStaticMesh(mesh);
				TextRender->SetText(row->Nome.ToString());
			}
		}
	}
}
